package com.itcast.rpc.core.codec;

import com.itcast.rpc.core.base.BaseRpcBean;
import com.itcast.rpc.core.util.HessianSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-23 14:13
 **/
public class RpcDecoder<T extends BaseRpcBean> extends ReplayingDecoder<Void> {
    private Class<T> clazz;
    
    public RpcDecoder(Class<T> clazz) {
        this.clazz = clazz;
    }
    
    private HessianSerializer hessianSerializer = new HessianSerializer();
    
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext,
                          ByteBuf byteBuf, List<Object> list) throws Exception {
        //读取序列化后的bytes
        int length = byteBuf.readInt();
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);
        
        //反序列化 
        BaseRpcBean rpcBean = hessianSerializer.deserialize(bytes, clazz);
        
        //加入list中
        list.add(rpcBean);
    }
}
